<?php

namespace Mlym\CodeGeneration\ControllerGeneration\Method;


use EasySwoole\ORM\Utility\Schema\Column;
use Mlym\CodeGeneration\Middleware\Bean\View\ViewColumnBean;

class Edit extends MethodAbstract
{

    protected $methodName = 'edit';
    protected $methodDescription = '更新数据';
    protected $methodAllow = 'POST';

    function addMethodBody()
    {
        $method = $this->method;
        $modelName = $this->getModelName();
        $table = $this->controllerConfig->getTable();

        $methodBody = <<<Body
\$param = ContextManager::getInstance()->get('param');
\$model = new {$modelName}();
\$info = \$model->get(['{$table->getPkFiledName()}' => \$param['{$table->getPkFiledName()}']]);
if (empty(\$info)) {
    \$this->writeJson(Status::CODE_BAD_REQUEST, [], '该数据不存在');
    return false;
}
\$updateData = array();

Body;
        $this->chunkSchemaColumn(function (ViewColumnBean $column) use (&$methodBody) {
            $param = $this->buildValidateColumnParam($column);
            $isPrimary = $this->controllerConfig->getTable()->getTableName() == $column->getModule() && $this->controllerConfig->getTable()->getPkFiledName() == $column->getName();
            if (!in_array($column->getName(), $this->ignoreField)) {
                if ($isPrimary){
                    $param->required = '';
                }else{
                    $param->optional = '';
                    $methodBody .= "\$updateData['{$column->getName()}']=\$param['{$column->getName()}'] ?? \$info->{$column->getName()};\n";
                }
                $this->addColumnComment($param);
            }
            return false;
        });

        $methodBody .= <<<Body
\$info->update(\$updateData);
\$this->writeJson(Status::CODE_OK, \$info, "操作成功");

Body;
        $method->setBody($methodBody);

    }


    function addComment()
    {
        $this->method->addComment("@throws \Throwable");
    }
}
